<template>
  <div class="log-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>操作日志</h2>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-form :model="searchForm" :inline="true" class="search-form">
            <el-form-item label="操作人">
              <el-input
                v-model="searchForm.operator"
                placeholder="请输入操作人"
                clearable
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="模块">
              <el-select v-model="searchForm.module" placeholder="请选择模块" clearable>
                <el-option label="作者管理" value="author" />
                <el-option label="图书管理" value="book" />
                <el-option label="分类管理" value="category" />
                <el-option label="出版社管理" value="publisher" />
                <el-option label="借阅管理" value="borrow" />
                <el-option label="用户管理" value="user" />
                <el-option label="系统管理" value="system" />
              </el-select>
            </el-form-item>
            <el-form-item label="操作类型">
              <el-select v-model="searchForm.operationType" placeholder="请选择操作类型" clearable>
                <el-option label="新增" value="CREATE" />
                <el-option label="修改" value="UPDATE" />
                <el-option label="删除" value="DELETE" />
                <el-option label="查询" value="SELECT" />
                <el-option label="登录" value="LOGIN" />
                <el-option label="退出" value="LOGOUT" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option label="成功" value="SUCCESS" />
                <el-option label="失败" value="FAILED" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6" class="text-right">
          <el-button 
            type="warning" 
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button type="danger" @click="handleClear">
            <el-icon><DeleteFilled /></el-icon>
            清空日志
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
        height="500"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="operator" label="操作人" width="100" />
        <el-table-column prop="module" label="模块" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="getModuleTagType(row.module)">
              {{ getModuleName(row.module) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operationType" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="getOperationTagType(row.operationType)">
              {{ getOperationName(row.operationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="操作描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="requestIp" label="IP地址" width="120" />
        <el-table-column prop="costTime" label="耗时(ms)" width="100">
          <template #default="{ row }">
            <span :class="getCostTimeClass(row.costTime)">{{ row.costTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag size="small" :type="row.status === 'SUCCESS' ? 'success' : 'danger'">
              {{ row.status === 'SUCCESS' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="操作时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
          <el-descriptions-item label="操作人">{{ currentLog.operator }}</el-descriptions-item>
          <el-descriptions-item label="模块">{{ getModuleName(currentLog.module) }}</el-descriptions-item>
          <el-descriptions-item label="操作类型">{{ getOperationName(currentLog.operationType) }}</el-descriptions-item>
          <el-descriptions-item label="类名">{{ currentLog.className }}</el-descriptions-item>
          <el-descriptions-item label="方法名">{{ currentLog.methodName }}</el-descriptions-item>
          <el-descriptions-item label="请求IP">{{ currentLog.requestIp }}</el-descriptions-item>
          <el-descriptions-item label="请求URL">{{ currentLog.requestUrl }}</el-descriptions-item>
          <el-descriptions-item label="耗时">{{ currentLog.costTime }}ms</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentLog.status === 'SUCCESS' ? 'success' : 'danger'">
              {{ currentLog.status === 'SUCCESS' ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作时间" :span="2">{{ formatDateTime(currentLog.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="操作描述" :span="2">{{ currentLog.description }}</el-descriptions-item>
          <el-descriptions-item label="请求参数" :span="2">
            <pre class="json-content">{{ formatJson(currentLog.params) }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="返回结果" :span="2">
            <pre class="json-content">{{ formatJson(currentLog.result) }}</pre>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentLog.errorMsg" label="错误信息" :span="2">
            <div class="error-msg">{{ currentLog.errorMsg }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete, DeleteFilled, Download, View } from '@element-plus/icons-vue'
// import logApi from '@/api/log'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const detailDialogVisible = ref(false)
const currentLog = ref(null)

// 搜索表单
const searchForm = reactive({
  operator: '',
  module: '',
  operationType: '',
  status: '',
  dateRange: null
})

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

// 获取日志列表（模拟数据）
const getLogList = async () => {
  try {
    loading.value = true
    
    // 模拟数据，实际应该调用 logApi.getList(params)
    const mockData = {
      records: [
        {
          id: 1,
          operator: 'admin',
          module: 'author',
          operationType: 'CREATE',
          description: '添加作者：张三',
          className: 'AuthorController',
          methodName: 'addAuthor',
          params: '{"name":"张三","nationality":"中国"}',
          result: '{"code":200,"message":"添加成功"}',
          status: 'SUCCESS',
          errorMsg: null,
          requestIp: '192.168.1.100',
          requestUrl: '/author/add',
          costTime: 125,
          createTime: new Date()
        },
        {
          id: 2,
          operator: 'admin',
          module: 'author',
          operationType: 'UPDATE',
          description: '修改作者：李四',
          className: 'AuthorController',
          methodName: 'updateAuthor',
          params: '{"id":1,"name":"李四","nationality":"中国"}',
          result: '{"code":200,"message":"修改成功"}',
          status: 'SUCCESS',
          errorMsg: null,
          requestIp: '192.168.1.100',
          requestUrl: '/author/update',
          costTime: 89,
          createTime: new Date(Date.now() - 3600000)
        },
        {
          id: 3,
          operator: 'user',
          module: 'user',
          operationType: 'LOGIN',
          description: '用户登录',
          className: 'UserController',
          methodName: 'login',
          params: '{"username":"user"}',
          result: '{"code":200,"message":"登录成功"}',
          status: 'SUCCESS',
          errorMsg: null,
          requestIp: '192.168.1.101',
          requestUrl: '/user/login',
          costTime: 234,
          createTime: new Date(Date.now() - 7200000)
        },
        {
          id: 4,
          operator: 'admin',
          module: 'author',
          operationType: 'DELETE',
          description: '删除作者失败',
          className: 'AuthorController',
          methodName: 'deleteAuthor',
          params: '{"id":999}',
          result: null,
          status: 'FAILED',
          errorMsg: '作者不存在',
          requestIp: '192.168.1.100',
          requestUrl: '/author/delete',
          costTime: 45,
          createTime: new Date(Date.now() - 10800000)
        }
      ],
      total: 4
    }
    
    tableData.value = mockData.records
    pagination.total = mockData.total
  } catch (error) {
    ElMessage.error('获取日志列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  getLogList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? null : ''
  })
  pagination.pageNum = 1
  getLogList()
}

// 查看详情
const handleView = (row) => {
  currentLog.value = row
  detailDialogVisible.value = true
}

// 删除日志
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这条日志记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // await logApi.delete(row.id)
    ElMessage.success('删除成功')
    getLogList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    const ids = selectedRows.value.map(row => row.id)
    
    await ElMessageBox.confirm(
      `确定要删除选中的${ids.length}条日志记录吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // await logApi.deleteBatch(ids)
    ElMessage.success('批量删除成功')
    getLogList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败: ' + error.message)
    }
  }
}

// 清空日志
const handleClear = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有日志记录吗？此操作不可恢复！',
      '清空确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // await logApi.clear()
    ElMessage.success('清空日志成功')
    getLogList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空日志失败: ' + error.message)
    }
  }
}

// 导出日志
const handleExport = async () => {
  try {
    ElMessage.info('导出功能开发中')
    // const params = { ...searchForm }
    // await logApi.export(params)
  } catch (error) {
    ElMessage.error('导出失败: ' + error.message)
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  getLogList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.pageNum = page
  getLogList()
}

// 获取模块名称
const getModuleName = (module) => {
  const moduleMap = {
    'author': '作者管理',
    'book': '图书管理',
    'category': '分类管理',
    'publisher': '出版社管理',
    'borrow': '借阅管理',
    'user': '用户管理',
    'system': '系统管理'
  }
  return moduleMap[module] || module
}

// 获取操作类型名称
const getOperationName = (operationType) => {
  const operationMap = {
    'CREATE': '新增',
    'UPDATE': '修改',
    'DELETE': '删除',
    'SELECT': '查询',
    'LOGIN': '登录',
    'LOGOUT': '退出'
  }
  return operationMap[operationType] || operationType
}

// 获取模块标签类型
const getModuleTagType = (module) => {
  const typeMap = {
    'author': 'primary',
    'book': 'success',
    'category': 'warning',
    'publisher': 'danger',
    'borrow': 'info',
    'user': '',
    'system': 'danger'
  }
  return typeMap[module] || ''
}

// 获取操作类型标签类型
const getOperationTagType = (operationType) => {
  const typeMap = {
    'CREATE': 'success',
    'UPDATE': 'warning',
    'DELETE': 'danger',
    'SELECT': 'info',
    'LOGIN': 'primary',
    'LOGOUT': ''
  }
  return typeMap[operationType] || ''
}

// 获取耗时样式类
const getCostTimeClass = (costTime) => {
  if (costTime > 1000) return 'cost-time-slow'
  if (costTime > 500) return 'cost-time-medium'
  return 'cost-time-fast'
}

// 格式化JSON
const formatJson = (jsonStr) => {
  if (!jsonStr) return ''
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch {
    return jsonStr
  }
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  getLogList()
})
</script>

<style scoped>
.log-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.text-right {
  text-align: right;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
}

.log-detail .json-content {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.4;
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-all;
}

.log-detail .error-msg {
  color: #f56c6c;
  background: #fef0f0;
  padding: 10px;
  border-radius: 4px;
  border-left: 4px solid #f56c6c;
}

.cost-time-fast {
  color: #67c23a;
}

.cost-time-medium {
  color: #e6a23c;
}

.cost-time-slow {
  color: #f56c6c;
}
</style>
